﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Calculator
{
    public partial class Form1 : Form
    {
        private string currentExpression = ""; // 当前表达式

        public Form1()
        {
            InitializeComponent();
            BindButtonEvents();
        }

        // 绑定所有按钮事件
        private void BindButtonEvents()
        {
            for (int i = 0; i < 10; i++)
            {
                var btn = Controls.Find($"btn{i}", true)[0] as Button;
                btn.Click += NumberButton_Click;
            }

            btnAdd.Click += OperatorButton_Click;
            btnSubtract.Click += OperatorButton_Click;
            btnMultiply.Click += OperatorButton_Click;
            btnDivide.Click += OperatorButton_Click;
            btnEqual.Click += EqualButton_Click;
            btnClear.Click += ClearButton_Click;
        }

        private void NumberButton_Click(object sender, EventArgs e)
        {
            var button = (Button)sender;
            currentExpression += button.Text;
            UpdateDisplay();
        }

        private void OperatorButton_Click(object sender, EventArgs e)
        {
            var button = (Button)sender;
            if (!string.IsNullOrEmpty(currentExpression))
            {
                currentExpression += $" {button.Text} ";
                UpdateDisplay();
            }
        }

        private void EqualButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(currentExpression)) return;
                // 使用DataTable计算表达式
                var result = new DataTable().Compute(currentExpression, null);
                txtDisplay.Text = $"{currentExpression} = {result}";
                currentExpression = result.ToString(); // 保留结果用于连续计算
            }
            catch (DivideByZeroException)
            {
                MessageBox.Show("错误：除数不能为零");
                ClearButton_Click(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无效表达式：{ex.Message}");
                ClearButton_Click(null, null);
            }
        }

        private void ClearButton_Click(object sender, EventArgs e)
        {
            currentExpression = "";
            txtDisplay.Clear();
        }

        private void UpdateDisplay()
        {
            txtDisplay.Text = currentExpression.Replace(" ", ""); // 紧凑显示
        }
    }
}
